# -*- coding: utf-8 -*-

from datetime import datetime
from dateutil import relativedelta
from itertools import groupby
from operator import itemgetter

import itertools
from odoo import api, fields, models, tools, _
from odoo.addons import decimal_precision as dp
from odoo.exceptions import UserError
from odoo.osv import expression
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.tools.float_utils import float_compare, float_round, float_is_zero



class ResGroups(models.Model):
    _inherit = 'res.groups'

    zcode = fields.Char(string="标识")

    #@api.multi
    def zbtn_insert(self):
        wiz_id = self.env["zres.groups.insert"].create({'dad_id': self.id})
        view_form = self.env.ref('fhgroups.wiz_form_zres_groups_insert')
        return {
            'name': u"载入权限组",
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form',
            'res_model': 'zres.groups.insert',
            'views': [(view_form.id, 'form')],
            'view_id': view_form.id,
            'target': 'new',
            'res_id': wiz_id.id,
            'context': self.env.context,
        }


class zres_groups_insert(models.TransientModel):
    _name = "zres.groups.insert"

    dad_id = fields.Many2one(comodel_name='res.groups', string='权限组', ondelete='cascade')
    group_id = fields.Many2one(comodel_name='res.groups', string='载入组', ondelete='cascade')

    #@api.multi
    def btn_conf(self):
        self.ensure_one()
        mids = []
        for model_access_line in self.dad_id.model_access:
            mkey = model_access_line.model_id.id
            mids.append(mkey)
        model_access = []
        for model_access_line in self.group_id.model_access:
            mkey = model_access_line.model_id.id
            if mkey not in mids:
                model_access.append([0, 0, {'name':  'name.%s.%s' %(model_access_line.model_id.model, self.dad_id.zcode),
                                            'model_id': mkey,
                                            'active': True,
                                            'perm_read': 1,
                                            'perm_write':0,
                                            'perm_create': 0,
                                            'perm_unlink': 0,
                                             }])
        self.dad_id.write({'model_access': model_access})